package handler

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"server/basic/config"
	"server/basic/dao"
	"server/basic/pkg"
	"server/basic/proto/user"
	"strconv"
)

type UserServer struct {
	user.UnimplementedUserServerServer
}

func (s *UserServer) UserLogin(_ context.Context, req *user.UserLoginReq) (*user.UserLoginResp, error) {
	login, err := dao.UserLogin(req.Name)
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	if login.Id == 0 {
		return nil, errors.New("用户不存在")
	}
	if login.Password != pkg.Md5(req.Password) {
		return nil, errors.New("密码错误")
	}
	return &user.UserLoginResp{UserId: int64(login.Id)}, nil
}
func (s *UserServer) PhoneLogin(_ context.Context, req *user.PhoneLoginReq) (*user.PhoneLoginResp, error) {
	key := fmt.Sprintf("login:%s", req.Phone)
	val, _ := config.Rdb.Get(context.Background(), key).Int()
	if int64(val) != req.CodePhone {
		return nil, errors.New("验证码不正确")
	}

	register, err := dao.UserRegister(req.Phone)
	if err != nil {
		return nil, err
	}
	if register.Id == 0 {
		return nil, err
	}
	return &user.PhoneLoginResp{UserId: int64(register.Id)}, nil
}
func (s *UserServer) PhoneSuccess(_ context.Context, req *user.PhoneSuccessReq) (*user.PhoneSuccessResp, error) {
	i := rand.Intn(9000) + 1000
	fmt.Println(i)
	phone, err := pkg.Phone(req.Phone, strconv.Itoa(i))
	if err != nil {
		return nil, err
	}
	if *phone.Body.Message != "OK" {
		return nil, err
	}
	redisPhone := dao.RedisPhone(req.Phone, i)
	if redisPhone == false {
		return nil, errors.New("验证码错误")
	}
	return &user.PhoneSuccessResp{}, nil
}
